{% extends 'base.html' %}
{% load i18n %}
{% load static %}
{% load sizeformat %}
{% load percentageformat %}
{% load tz %}

{% block title %}{% translate '资源统计列表' %}{% endblock %}

{% block head %}
    <link rel="stylesheet" type="text/css" href="{% static 'reports/reports.css' %}">
    <style>
        .nav-pills .nav-link.active, .nav-pills .show > .nav-link {
            font-weight: normal;
            background-color: #e0dfdf;
            color: #007bff!important;
        }

        .nav-pills .nav-link {
            padding-left: 30px;
        }
    </style>
{% endblock %}

{% block boby %}
    <div class="container-fluid d-flex flex-column h-100">
        <div class="d-flex px-3" style="margin-bottom: 10px">
{#            <nav aria-label="breadcrumb">#}
{#                <ol class="breadcrumb">#}
{#                    <li class="breadcrumb-item active" aria-current="page">{% translate '全部' %}</li>#}
{#                </ol>#}
{#            </nav>#}

            <a class="btn btn-outline-primary" href="{% url 'log-record:log-record-list' %}">{% translate '用户操作日志' %}</a>
        </div>
        <div class="d-flex px-3" style="flex: 1">
            <div style="width: 200px">
                <ul class="list-unstyled">
                    <li>
                        <button class="btn">
                            <span class="text-primary">资源统计管理</span>
                        </button>
                        <ul class="nav flex-column nav-pills" role="tablist" aria-orientation="vertical" id="resource-btn">
                            <li class="nav-item">
                                <a class="nav-link active" data-toggle="tab" href="#host" aria-controls="host"
                                   aria-selected="false" onclick="deleteButtonActive('resource-btn')">{% translate '宿主机' %}</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" data-toggle="tab" href="#center" aria-controls="center"
                                   aria-selected="true" onclick="deleteButtonActive('resource-btn')">{% translate '数据中心' %}</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" data-toggle="tab" href="#host_group" aria-controls="host_group"
                                   aria-selected="false" onclick="deleteButtonActive('resource-btn')">{% translate '宿主机组' %}</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link" data-toggle="tab" href="#quota" aria-controls="host_quota"
                                   aria-selected="false" onclick="deleteButtonActive('resource-btn')">{% translate '资源配额占比' %}</a>
                            </li>

                        </ul>
                    </li>
                    <li>
                        <button class="btn">
                            <span class="text-primary">用户操作日志</span>
                        </button>
                        <ul class="nav flex-column nav-pills" role="tablist" aria-orientation="vertical" id="user-log-btn">
                            <li class="nav-item">
                                <a class="nav-link" data-toggle="tab" href="#user_log"
                                   aria-controls="user_log"
                                   aria-selected="false" onclick="deleteButtonActive('user-log-btn')">{% translate '查询日志' %}</a>
                            </li>
                        </ul>
                    </li>
                </ul>

            </div>
            <div class="pl-lg-1 flex-grow-1">
                <div class="tab-content h-100">

                    <div class="card tab-pane fade show h-100" id="center" role="tabpanel"
                         aria-labelledby="center-tab">
                        <table class="table">
                            <thead class="thead-light">
                            <tr>
                                <th>{% translate '数据中心' %}</th>
                                <th>{% translate '总物理cpu(/核)' %}</th>
                                <th>{% translate '总虚拟cpu(/核)' %}</th>
                                <th>{% translate '已分配cpu(/核)' %}</th>
                                <th>cpu{% translate '分配率' %}</th>
                                <th>{% translate '总内存' %}</th>
                                <th>{% translate '已使用内存' %}</th>
                                <th>{% translate '内存使用率' %}</th>
                                <th>{% translate '虚拟机数' %}</th>
                            </tr>
                            </thead>
                            <tbody>
                            {% for c in centers %}
                                <tr>
                                    <td><a href="{% url 'reports:reports-center' id=c.id %}">{{ c.name }}</a></td>
                                    <td>{{ c.real_cpu }}</td>
                                    <td>{{ c.vcpu_total }}</td>
                                    <td>{{ c.vcpu_allocated }}</td>
                                    <td>{{ c.vcpu_allocated | percentageformat:c.vcpu_total }}</td>
                                    <td>{{ c.mem_total | sizeformat:'GB' }}</td>
                                    <td>{{ c.mem_allocated | sizeformat:'GB' }}</td>
                                    <td>{{ c.mem_allocated | percentageformat:c.mem_total }}</td>
                                    <td>{{ c.vm_created }}</td>
                                </tr>
                            {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    <div class="card tab-pane fade show h-100" id="host_group" role="tabpanel"
                         aria-labelledby="host_group-tab">
                        <table class="table">
                            <thead class="thead-light">
                            <tr>
                                <th>{% translate '宿主机组' %}</th>
                                <th>{% translate '数据中心' %}</th>
                                <th>{% translate '总物理cpu(/核)' %}</th>
                                <th>{% translate '总虚拟cpu(/核)' %}</th>
                                <th>{% translate '已分配cpu(/核)' %}</th>
                                <th>cpu{% translate '分配率' %}</th>
                                <th>{% translate '总内存' %}</th>
                                <th>{% translate '已使用内存' %}</th>
                                <th>{% translate '内存使用率' %}</th>
                                <th>{% translate '虚拟机数' %}</th>
                            </tr>
                            </thead>
                            <tbody>
                            {% for c in groups %}
                                <tr>
                                    <td><a href="{% url 'reports:reports-group' id=c.id %}">{{ c.name }}</a></td>
                                    <td>{{ c.center__name }}</td>
                                    <td>{{ c.real_cpu }}</td>
                                    <td>{{ c.vcpu_total }}</td>
                                    <td>{{ c.vcpu_allocated }}</td>
                                    <td>{{ c.vcpu_allocated | percentageformat:c.vcpu_total }}</td>
                                    <td>{{ c.mem_total | sizeformat:'GB' }}</td>
                                    <td>{{ c.mem_allocated | sizeformat:'GB' }}</td>
                                    <td>{{ c.mem_allocated | percentageformat:c.mem_total }}</td>
                                    <td>{{ c.vm_created }}</td>
                                </tr>
                            {% endfor %}
                            </tbody>
                        </table>
                    </div>
                    <div class="card  tab-pane fade show h-100 active" id="host" role="tabpanel"
                         aria-labelledby="host-tab">

                        <form role="form" class="form-horizontal" method="get" action="">
                            <div class="input-group" style="">
                                <div class="input-group-prepend">
                                    <label class="input-group-text" for="id-center">{% translate '数据中心' %}</label>
                                </div>
                                <select name="center" class="custom-select" id="id-center">
                                    {% if centers.count > 1 %}
                                        <option value="">--</option>
                                    {% elif centers is None %}
                                        <option value="">--</option>
                                    {% endif %}
                                    {% for c in centers %}
                                        <option value="{{ c.id }}" {% if c.id == center_id %}selected{% endif %}>
                                            {{ c.name }}
                                        </option>
                                    {% endfor %}
                                </select>
                                <div class="input-group-prepend">
                                    <label class="input-group-text" for="id-group">{% translate '主机组' %}</label>
                                </div>
                                <select name="group" class="custom-select" id="id-group">
                                    {% if groups.count > 1 %}
                                        <option value="">--</option>
                                    {% elif groups is None %}
                                        <option value="">--</option>
                                    {% endif %}
                                    {% for g in groups %}
                                        <option value="{{ g.id }}" {% if g.id == group_id|add:0 %}
                                                selected {% endif %}>{{ g.name }}</option>
                                    {% endfor %}
                                </select>
                                <div class="input-group-prepend">
                                    <label class="input-group-text" for="id-host">{% translate '宿主机' %}</label>
                                </div>
                                <select name="host" class="custom-select" id="id-host">
                                    {% if hosts.count > 1 %}
                                        <option value="">--</option>
                                    {% elif hosts is None %}
                                        <option value="">--</option>
                                    {% endif %}
                                    {% for h in hosts %}
                                        <option value="{{ h.id }}" {% if h.id == host_id|add:0 %}
                                                selected {% endif %}>{{ h.ipv4 }}</option>
                                    {% endfor %}
                                </select>
                                {#                                <div class="input-group-prepend">#}
                                {#                                    <label class="input-group-text" for="id-user">{% translate '创建者' %}</label>#}
                                {#                                </div>#}
                                {#                                <select name="user" class="custom-select" id="id-user">#}
                                {#                                    <option value="">--</option>#}
                                {#                                    {% for u in users %}#}
                                {#                                        <option value="{{ u.id }}"#}
                                {#                                                {% if u.id == user_id %}selected {% endif %}>{{ u.username }}</option>#}
                                {#                                    {% endfor %}#}
                                {#                                </select>#}
                                <div class="input-group-prepend">
                                    <label class="input-group-text">{% translate '关键字' %}</label>
                                </div>
                                <input type="text" class="form-control" name="search" value="{{ search }}"
                                       placeholder="{% translate '搜 IP地址' %}"/>
                                <span class="input-group-text"></span>
                                <button type="submit"
                                        class="btn btn-primary form-control">{% translate '筛选' %}</button>
                                {% if user.is_superuser %}
                                    {#                                    <button type="button" class="btn btn-primary" data-toggle="modal"#}
                                    {#                                            data-target="#exampleModal2"#}
                                    {#                                            style="color: #fff; margin-right: 10px; margin-left: 10px"> {% translate '批量保存' %} </button>#}

                                    {#                                    <button type="button" class="btn btn-primary" data-toggle="modal"#}
                                    {#                                            data-target="#exampleModal">#}
                                    {#                                        {% translate '一键检测' %}#}
                                    {#                                    </button>#}

                                    <button type="button" class="btn btn-primary" id="batch-save"
                                            style="color: #fff; margin-right: 10px; margin-left: 10px"> {% translate '批量保存' %} </button>
                                    <button type="button" class="btn btn-primary" id="one-click-detection">
                                        {% translate '一键检测' %}
                                    </button>
                                {% endif %}


                            </div>
                        </form>

                        <p></p>
                        <table class="table text-center">
                            <thead class="thead-light">
                            <tr>
                                <th>{% translate '机组' %}</th>
                                <th>{% translate '宿主机IP地址' %}</th>
                                <th>{% translate '虚拟机数' %}</th>
                                <th>{% translate '物理cpu核' %}</th>
                                <th>{% translate '虚拟CPU核:' %} <br> {% translate '已用/总数/利用率' %}</th>
                                <th>{% translate '虚拟内存GB:' %} <br> {% translate '已分配/总数/分配率' %} </th>
                                <th>{% translate '实际大页内存GB:' %} <br> {% translate '已分配/总数/利用率' %}</th>

                                {% if user.is_superuser %}
                                    <th>{% translate '操作' %}</th>
                                {% endif %}
                            </tr>
                            </thead>
                            <tbody id="tbody-host">
                            {% for c in hosts %}
                                <tr>
                                    <td>{{ c.group__name }}</td>
                                    <td>{{ c.ipv4 }}</td>
                                    <td>{{ c.vm_created }}</td>
                                    <td>{{ c.real_cpu }}</td>
                                    <td>{{ c.vcpu_allocated }} / {{ c.vcpu_total }}
                                        / {{ c.vcpu_allocated | percentageformat:c.vcpu_total }}</td>
                                    <td>{{ c.mem_allocated }} / {{ c.mem_total }}
                                        / {{ c.mem_allocated | percentageformat:c.mem_total }}</td>
                                    <td>未检测 / 未检测 / 未检测</td>
                                    {% if  user.is_superuser %}
                                        <td><a type="button" class="btn btn-primary"
                                               onclick='detectionHost( this ,"{{ c.ipv4 }}", "{{ csrf_token }}")'
                                               style="color: #fff;">检测</a>
                                            | <a
                                                    type="button"
                                                    class="btn btn-primary" style="color: #fff;"
                                                    onclick="saveHostInfo(this, '{{ c.ipv4 }}', '{{ csrf_token }}')">保存</a>
                                        </td>
                                    {% endif %}
                                </tr>
                            {% endfor %}


                            </tbody>

                        </table>

                    </div>
                    <div class="card tab-pane fade show h-100" id="quota" role="tabpanel"
                         aria-labelledby="quota-tab">
                        <div class="container-fluid col-lg-12">
                            <div class="pt-4 pb-4">
                                <p class="font-weight-bold">{% translate '资源配额概况' %}</p>
                            </div>
                            <div class="row">
                                <div class="col-12 col-sm-4 col-md-3">
                                    <canvas id="id-chart-cpu" height=""></canvas>
                                </div>
                                <div class="col-12 col-sm-4 col-md-3">
                                    <canvas id="id-chart-mem" height=""></canvas>
                                </div>
                                <div class="col-12 col-sm-4 col-md-3">
                                    <canvas id="id-chart-ips" height=""></canvas>
                                </div>
                                <div class="col-12 col-sm-4 col-md-3">
                                    <canvas id="id-chart-vm" height=""></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                    <!-- 日志 -->
                    <div class="card tab-pane fade show h-100" id="user_log" role="tabpanel"
                         aria-labelledby="center-tab">

                        <div class="card">
                            <div class="card-header">
                <span class="card-title"><strong><a href="{% url 'log-record:log-record-list' %}"
                                                    class="btn btn-outline-primary">{% translate '用户操作日志' %} ({{ count }})</a></strong></span>
                            </div>

                            <table class="table table-hover text-center table-vm-list"
                                   style="word-wrap:break-word;word-break:break-all;">
                                <thead class="thead-light">
                                <tr>
                                    <th>{% translate '序号' %}</th>
                                    <th>{% translate '用户名/IP' %}</th>
                                    <th>{% translate '操作内容' %}</th>
                                    <th>{% translate '操作时间' %} <span>{{ request.session.useTimeZoneOffset }}</span></th>
                                </tr>
                                </thead>
                                <tbody>
                                {% for obj in page %}
                                    <tr>
                                        <td>{{ forloop.counter| add:page_start_index }}</td>
                                        {% if obj.real_user and obj.request_ip %}
                                            <td>cstcloud:{{ obj.real_user }}{{ obj.request_ip }}</td>
                                        {% elif obj.real_user %}
                                            <td>cstcloud:{{ obj.real_user }}</td>
                                        {% elif obj.username and obj.request_ip %}
                                            <td>{{ obj.username }}/{{ obj.request_ip }}</td>
                                        {% elif obj.username %}
                                            <td>{{ obj.username }}</td>
                                        {% else %}
                                            <td></td>
                                        {% endif %}
                                        <td class="text-left">{{ obj.operation_content }}</td>
                                        {% timezone request.session.useTimeZone|default:'UTC' %}
                                        <td>{{ obj.create_time|date:'Y-m-d H:i:s' }}</td>
                                        {% endtimezone %}
                                    </tr>
                                {% endfor %}
                            </table>
                            {% with page_list=page_nav.page_list previous=page_nav.previous next=page_nav.next %}
                                {% if page_list %}
                                    <div class="card-footer">
                                        <nav aria-label="Page navigation">
                                            <ul class="pagination" style="margin:0;">
                                                {% if previous %}
                                                    <li class="page-item"><a class="page-link"
                                                                             href="?{{ previous }}"
                                                                             aria-label="Previous"><span
                                                            aria-hidden="true">&laquo;</span></a></li>
                                                {% else %}
                                                    <li class="page-item disable"><span class="page-link"
                                                                                        aria-hidden="true">&laquo;</span>
                                                    </li>
                                                {% endif %}
                                                {% for disp, query, active in page_list %}
                                                    {% if active %}
                                                        <li class="page-item active"><a class="page-link"
                                                                                        href="?{{ query }}">{{ disp }}</a>
                                                        </li>
                                                    {% else %}
                                                        <li class="page-item"><a class="page-link"
                                                                                 href="?{{ query }}">{{ disp }}</a>
                                                        </li>
                                                    {% endif %}
                                                {% endfor %}
                                                {% if next %}
                                                    <li class="page-item"><a class="page-link"
                                                                             href="?{{ next }}"
                                                                             aria-label="Next"><span
                                                            aria-hidden="true">&raquo;</span></a></li>
                                                {% else %}
                                                    <li class="page-item disable"><span class="page-link"
                                                                                        aria-hidden="true">&raquo;</span>
                                                    </li>
                                                {% endif %}
                                            </ul>
                                        </nav>
                                    </div>
                                {% endif %}
                            {% endwith %}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">ip 范围</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form>
                        <div class="input-group mb-3">
                            <label for="staticEmail" class="">宿主机组</label>
                            <div class="col-sm-10">
                                <select name="group" class="custom-select" id="id-group-batchdetect">
                                    <option value="">--</option>
                                    {% for g in groups %}
                                        <option value="{{ g.id }}" {% if g.id == group_id|add:0 %}
                                                selected {% endif %}>{{ g.name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                        <div class="input-group mb-3">

                            <input type="text" class="form-control" aria-label="Sizing example input"
                                   aria-describedby="inputGroup-sizing-default" placeholder="起始地址" id="ip-start">
                        </div>
                        <div class="input-group mb-3">

                            <input type="text" class="form-control" aria-label="Sizing example input"
                                   aria-describedby="inputGroup-sizing-default" placeholder="结束地址" id="ip-end">
                        </div>
                        <div class="input-group mb-3">
                            <input type="text" class="form-control" aria-label="Sizing example input"
                                   aria-describedby="inputGroup-sizing-default"
                                   placeholder="子网/掩码 例如：192.168.0/255.255.255.0" id="ip-subnet">
                        </div>

                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="batchdetection-ip">提交</button>
                </div>
            </div>
        </div>
    </div>

    <div class="modal fade" id="exampleModal2" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel2">ip 范围</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <form>
                        <div class="form-group row">
                            <label for="staticEmail" class="col-sm-2 col-form-label">宿主机组</label>
                            <div class="col-sm-10">
                                <select name="group" class="custom-select" id="id-group-savedetect">
                                    <option value="">--</option>
                                    {% for g in groups %}
                                        <option value="{{ g.id }}" {% if g.id == group_id|add:0 %}
                                                selected {% endif %}>{{ g.name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                        <div class="form-group row">
                            <label for="staticEmail" class="col-sm-2 col-form-label">部门</label>
                            <div class="col-sm-10">
                                <select name="group" class="custom-select" id="id-room-savedetect">
                                    <option value="">--</option>
                                    {% for r in room %}
                                        <option value="{{ r.id }}">{{ r.name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>


                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                    <button type="button" class="btn btn-primary" id="savedetection-ip">提交</button>
                </div>
            </div>
        </div>
    </div>

{% endblock %}

{% block script %}
    <script type="text/javascript" src="{% static 'chartjs/chart-3.4.1.min.js' %}"></script>
    <script type="text/javascript" src="{% static 'reports/reports_common.js' %}"></script>
    <script>
        {% verbatim script %}
            window.onload = function () {

                initQuotaCharts();
            };
            function create_chart(dom_canvas, title, subtitle, data) {
                return new Chart(
                    dom_canvas, {
                        type: 'pie',
                        options: {
                            plugins: {
                                title: {
                                    display: true,
                                    text: title,
                                    align: 'center',
                                    position: 'bottom'
                                },
                                subtitle: {
                                    display: true,
                                    text: subtitle,
                                    position: 'bottom'
                                }
                            }
                        },
                        data: {
                            labels: ['已用', '可用'],
                            datasets: [{
                                label: '已用',
                                backgroundColor: [window.chartColors.grey, window.chartColors.green],
                                data: [data.used, data.total - data.used]
                            }]
                        }
                    }
                );
            }
        {% endverbatim script %}
        function initQuotaCharts() {
            let cpu_total = {{ quota.vcpu_total }};
            let cpu_used = {{ quota.vcpu_allocated }};
            let mem_total = {{ quota.mem_total }};
            let mem_used = {{ quota.mem_allocated }};
            let ips_total = {{ quota.ips_total }};
            let ips_used = {{ quota.ips_used }};
            let vm_total = {{ quota.vm_limit }};
            let vm_used = {{ quota.vm_created }};

            let mem_title = '{% translate '内存' %} (' + sizeFormat(mem_total, "GB") + ')'
            let vcpu_subtitle = "{% translate '已使用' %} " + cpu_used + " of " + cpu_total;
            let mem_subtitle = "{% translate '已使用' %} " + mem_used + "Gb of " + mem_total + "Gb";
            let ips_subtitle = "{% translate '已使用' %} " + ips_used + " of " + ips_total;
            let vm_subtitle = "{% translate '已使用' %} " + vm_used + " of " + vm_total;

            let canvas_mem = document.getElementById('id-chart-mem').getContext('2d');
            let canvas_cpu = document.getElementById('id-chart-cpu').getContext('2d');
            let canvas_vm = document.getElementById('id-chart-vm').getContext('2d');
            let canvas_ips = document.getElementById('id-chart-ips').getContext('2d');

            create_chart(canvas_cpu, '{% translate 'VCPU数' %}', vcpu_subtitle, {total: cpu_total, used: cpu_used});
            create_chart(canvas_mem, mem_title, mem_subtitle, {total: mem_total, used: mem_used});
            create_chart(canvas_ips, '{% translate 'IP地址数' %}', ips_subtitle, {total: ips_total, used: ips_used});
            create_chart(canvas_vm, '{% translate '虚拟机数' %}', vm_subtitle, {total: vm_total, used: vm_used});
        }
    </script>

    <script type="text/javascript" src="{% static 'reports/reports_list.js' %}"></script>
    <script>
        $("#host").addClass("active");
        $("#nav_reports").addClass("active");

        const btn1 = document.getElementById('resource-btn');
        const btn2 = document.getElementById('user-log-btn');

        function deleteButtonActive(obj) {

            // 检查 btn1 的子节点中是否有 active 类
            if (obj === btn1.id){
                Array.from(btn2.getElementsByClassName('active')).forEach(activeButton => {
                    activeButton.classList.remove('active');
                });
            }else {
                Array.from(btn1.getElementsByClassName('active')).forEach(activeButton => {
                    activeButton.classList.remove('active');
                });
            }
        }

        // 获取当前 URL 的查询参数
        const urlParams = new URLSearchParams(window.location.search);

        // 检查是否存在 'page' 参数
        const page = urlParams.get('page');
        // 如果存在 'page' 参数，则为对应的 li 添加 active 类
        if (page) {
            const elements = document.querySelectorAll('a[href="#user_log"]');
            Array.from(btn1.getElementsByClassName('active')).forEach(activeButton => {
                activeButton.classList.remove('active');
            });
            elements.forEach(element => {
                {#element.classList.add('active');#}
                simulateMouseClick(element);

            });

        }

        // 模拟鼠标点击的函数
        function simulateMouseClick(element) {
            // 创建一个新的 MouseEvent
            const mouseEvent = new MouseEvent('click', {
                bubbles: true,  // 事件是否应该冒泡
                cancelable: true,  // 事件是否可以被取消
                view: window   // 事件的视图，通常为 window
            });

            // 触发事件
            element.dispatchEvent(mouseEvent);
        }


    </script>

{% endblock %}
